<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 提示区域 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数！" :closable="false" type="warning" show-icon></el-alert>
      <!-- 选择商品分类 -->
      <div class="selectCate">
        选择商品分类：
        <el-cascader
          v-model="selectedKeys"
          :options="cateList"
          :props="cascaderProps"
          @change="cascaderChange"
        ></el-cascader>
      </div>
      <!-- 标签页区域 -->
      <el-tabs v-model="activeName" @tab-click="tabsClick">
        <!-- 添加动态参数的面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            @click="addDialogVisible = true"
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
          >添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTabData" style="width: 100%" stripe border>
            <el-table-column type="expand">
              <!-- 动态参数标签 -->
              <template slot-scope="props">
                <el-tag
                  @close="handleClose(index,props.row)"
                  v-for="(tag,index) in props.row.attr_vals"
                  :key="index"
                  closable
                >{{tag}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="props.row.inputVisible"
                  v-model="props.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(props.row)"
                  @blur="handleInputConfirm(props.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(props.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 修改 -->
                <el-button
                  @click="showEditDialog(scope.row)"
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                ></el-button>
                <!-- 删除 -->
                <el-button
                  @click="removeParams(scope.row.attr_id)"
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性的面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            @click="addDialogVisible = true"
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
          >添加属性</el-button>
          <!-- 静态参数表格 -->
          <el-table :data="onlyTabData" style="width: 100%" stripe border>
            <el-table-column type="expand">
              <!-- 静态参数标签 -->
              <template slot-scope="props">
                <el-tag
                  @close="handleClose(index,props.row)"
                  v-for="(tag,index) in props.row.attr_vals"
                  :key="index"
                  closable
                >{{tag}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="props.row.inputVisible"
                  v-model="props.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(props.row)"
                  @blur="handleInputConfirm(props.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(props.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 修改 -->
                <el-button
                  @click="showEditDialog(scope.row)"
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                ></el-button>
                <!-- 删除 -->
                <el-button
                  @click="removeParams(scope.row.attr_id)"
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数的对话框 -->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="closeAddCate"
    >
      <el-form :model="addForm" :rules="addFormRule" ref="addForm" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数的对话框 -->
    <el-dialog
      :title="'修改'+titleText"
      :visible.sync="deitDialogVisible"
      width="50%"
      @close="closeDeitCate"
    >
      <el-form :model="deitForm" :rules="deitFormRule" ref="deitForm" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="deitForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deitDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="deitParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      cateList: [],
      // 选中存储数据
      selectedKeys: [],
      // 级联选择器配置对象
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        // 次级菜单的展开方式
        expandTrigger: 'hover'
      },
      // 标签页默认选择的标签
      activeName: 'many',
      // 动态参数列表
      manyTabData: [],
      // 静态参数列表
      onlyTabData: [],
      // 控制添加对话框的显示与隐藏
      addDialogVisible: false,
      // 控制编辑对话框的显示与隐藏
      deitDialogVisible: false,
      // 添加参数的表单
      addForm: {
        attr_name: ''
      },
      // 修改参数的表单
      deitForm: {},
      // 校验添加分类表单的校验规则
      addFormRule: {
        attr_name: [
          { required: true, message: '请输入参数', trigger: 'blur' },
          { min: 2, max: 7, message: '长度在 2 到 7 个字符', trigger: 'blur' }
        ]
      },
      // 校验修改分类表单的校验规则
      deitFormRule: {
        attr_name: [
          { required: true, message: '请输入参数', trigger: 'blur' },
          { min: 2, max: 7, message: '长度在 2 到 7 个字符', trigger: 'blur' }
        ]
      }
    }
  },

  created () {
    this.getCateList()
  },

  methods: {
    // 获取商品分类数据
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
    },
    // 级联选择器发生变化
    async cascaderChange () {
      this.getParmsData()
    },
    // 点击tabs标签页触发
    tabsClick () {
      this.getParmsData()
    },
    // 获取参数
    async getParmsData () {
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.manyTabData = []
        this.onlyTabData = []
        return
      }
      const { data: res } = await this.$http.get(`categories/${this.catdId}/attributes`, {
        params: {
          sel: this.activeName
        }
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals !== '' ? item.attr_vals.split(' ') : []
        // 控制添加标签的显示与隐藏
        item.inputVisible = false
        // 添加标签的内容
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTabData = res.data
      } else {
        this.onlyTabData = res.data
      }
    },
    // 关闭添加对话框
    closeAddCate () {
      this.$refs.addForm.resetFields()
    },
    // 关闭编辑对话框
    closeDeitCate () {
      this.$refs.deitForm.resetFields()
    },
    // 点击确认，添加参数
    addParams () {
      // 先验证参数是否合法
      this.$refs.addForm.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$http.post(`categories/${this.catdId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
      })
      // 关闭对话框
      this.addDialogVisible = false
      // 刷新页面
      this.getParmsData()
    },
    // 点击删除
    async removeParams (id) {
      this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 点击确认
        const { data: res } = await this.$http.delete(`categories/${this.catdId}/attributes/${id}`)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getParmsData()
      }).catch(() => {
        // 点击取消
        this.$message.info('已取消删除')
      })
    },
    // 点击修改
    async showEditDialog (row) {
      const id = row.attr_id
      const { data: res } = await this.$http.get(`categories/${this.catdId}/attributes/${id}`, {
        params: { attr_sel: this.activeName }
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.deitForm = res.data
      this.deitDialogVisible = true
    },
    // 确认修改
    deitParams () {
      this.$refs.deitForm.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.catdId}/attributes/${this.deitForm.attr_id}`, {
          attr_name: this.deitForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.deitDialogVisible = false
        this.getParmsData()
      })
    },
    // 点击新建标签
    showInput (row) {
      row.inputVisible = !row.inputVisible
      // $nextTick 方法的作用：就是当页面的元素被重新渲染之后，才会执行回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 添加参数项
    async handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue)
      this.sloseTag(row)
      row.inputValue = ''
      row.inputVisible = false
    },
    // 删除参数项
    async handleClose (index, row) {
      row.attr_vals.splice(index, 1)
      this.sloseTag(row)
    },
    // 添加删除参数项函数
    async sloseTag (row) {
      const { data: res } = await this.$http.put(`categories/${this.catdId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
    }
  },
  computed: {
    // 控制按钮是否禁用
    isBtnDisabled () {
      return (this.selectedKeys.length !== 3)
      // if (this.selectedKeys.length !== 3) {
      //   return true
      // }
      // return false
    },
    // 三级分类id
    catdId () {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return ''
    },
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态参数'
    }
  }
}
</script>

<style scoped lang='less'>
.el-alert {
  margin-bottom: 14px;
}
.el-table {
  margin-top: 14px;
}
.el-tag {
  margin: 5px;
}
.input-new-tag {
  width: 120px;
}
</style>
